package com.vitabuybuy.tv.ui.mine.dredge

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.view.View
import androidx.core.content.ContextCompat
import androidx.lifecycle.Observer
import com.library.common.base.BaseActivity
import com.library.common.base.MessageModel
import com.luck.picture.lib.PictureSelector
import com.library.common.BuildConfig
import com.library.common.ext.setOnclickNoRepeat
import com.library.common.net.NetUrl
import com.vitabuybuy.tv.R
import com.vitabuybuy.tv.databinding.ActivityDredgeStoreBinding
import com.vitabuybuy.tv.dialog.CategroyPopup
import com.vitabuybuy.tv.dialog.OptionsDialog
import com.vitabuybuy.tv.dto.FirstCategoryDto
import com.vitabuybuy.tv.dto.RegionDto

import com.library.common.toast.XToast
import com.library.common.util.PictureUtils
import com.vitabuybuy.tv.adaptebinding.ImageAdapter.setNomalImageUrl
import com.vitabuybuy.tv.dialog.AreaCodePopup
import com.vitabuybuy.tv.ui.UniversalityResultActivity
import com.vitabuybuy.tv.ui.mine.dredge.viewmodel.DredgeStoreViewModel
import com.vitabuybuy.tv.widget.selector.BottomDialog
import com.vitabuybuy.tv.widget.selector.SelectedListener
import com.yanzhenjie.permission.AndPermission
import com.yanzhenjie.permission.runtime.Permission
import kotlinx.android.synthetic.main.activity_dredge_store.*
import kotlinx.android.synthetic.main.activity_dredge_store.countryCodePicker
import kotlinx.android.synthetic.main.activity_dredge_store.llContainer
import kotlinx.android.synthetic.main.activity_phone_login.*
import java.util.ArrayList

class DredgeStoreActivity : BaseActivity<DredgeStoreViewModel, ActivityDredgeStoreBinding>() {
    override val isUseBaseTitleBar: Boolean
        get() = true
    override val layoutId: Int
        get() = R.layout.activity_dredge_store

    private var identityFrontImage = ""
    private var identityBackImage = ""
    private var holdingIdentityImage = ""
    private var businessLicenseImage = ""
    private var bankLicenseImage = ""
    private var shopType = ""
    private var categoryId = -1
    private var requestCode = 0
    private var regionId = -1
    private val picDialog by lazy { OptionsDialog(mContext) }
    private val genderDialog by lazy { OptionsDialog(mContext) }
    private var areaDialog: BottomDialog? = null
    private var defaultAreaCode = "86"

    override fun initView(savedInstanceState: Bundle?) {
        setTitle(getString(R.string.check_shop))
        shopType = getString(R.string.individual)
    }

    override fun observeData() {
        viewModel.getDredgeStoreInfo()
        viewModel.storeInfo.observe(this, Observer {
            if (it == null || it.status == null) {
                return@Observer
            }
            when (it.status) {
                getString(R.string.under_review) -> {
                    llContainer.setEnable(false)
                    btnSubmitApply.apply {
                        text = getString(R.string.under_review)
                        setTextColor(ContextCompat.getColor(mContext, R.color.text_999999))
                        setNormalSolid(ContextCompat.getColor(mContext, R.color.color_bdc2c8))
                        isEnabled = false
                    }
                }
                getString(R.string.pass) -> {
                    btnSubmitApply.apply {
                        text = getString(R.string.pass)
                        setTextColor(ContextCompat.getColor(mContext, R.color.text_999999))
                        setNormalSolid(ContextCompat.getColor(mContext, R.color.color_bdc2c8))
                        isEnabled = false
                    }
                }
                getString(R.string.refuse) -> {
                    tvGroupDeadline.apply {
                        visibility = View.VISIBLE
                        text = context.getString(R.string.reson) + it.refuseReason
                    }
                    btnSubmitApply.apply {
                        text = context.getString(R.string.apply_again)
                    }
                }
            }
            identityFrontImage = it.identityFrontImage
            identityBackImage = it.identityBackImage
            holdingIdentityImage = it.holdingIdentityImage
            shopType = it.type
            categoryId = it.category.id
            tvShopCategory.text = it.category.name
            tvShopType.text = shopType
            etShopName.setText(it.name)
            etContactPerson.setText(it.contactName)
            etContactWay.setText(it.contactPhone)
            if(it.phone.startsWith("86")){
                defaultAreaCode = "86"
            }else if(it.phone.startsWith("60")){
                defaultAreaCode = "60"
            }
            countryCode.text = "+${defaultAreaCode}"
            etDetailAddress.setText(it.address)
            if (it.regionList != null) {
                when (it.regionList.size) {
                    0 -> {
                    }
                    1 -> {
                        countryCodePicker.text = it.regionList[0].name
                        tvShopAddress.text = it.regionList[0].name
                        regionId = it.regionList[0].id
                    }
                    else -> {
                        countryCodePicker.text = it.regionList[0].name
                        var regionStr = "";
                        for ((index, region) in it.regionList.withIndex()) {
                            if (index != 0) {
                                regionStr += region.name
                            }
                            regionId = region.id
                        }
                        tvShopAddress.text = regionStr
                    }
                }
            }
            setNomalImageUrl(
                ivIdCardPositiveSide,
                identityFrontImage,
                ContextCompat.getDrawable(mContext, R.drawable.icon_navbar_add)
            )
            setNomalImageUrl(
                ivIdCardNegativeSide,
                identityBackImage,
                ContextCompat.getDrawable(mContext, R.drawable.icon_navbar_add)
            )
            setNomalImageUrl(
                ivHandWithIdCard,
                holdingIdentityImage,
                ContextCompat.getDrawable(mContext, R.drawable.icon_navbar_add)
            )
            if (shopType == getString(R.string.enterprise)) {
                businessLicenseImage = it.businessLicenseImage
                bankLicenseImage = it.bankLicenseImage
                setNomalImageUrl(
                    ivShopLicense,
                    businessLicenseImage,
                    ContextCompat.getDrawable(mContext, R.drawable.icon_navbar_add)
                )
                setNomalImageUrl(
                    ivOpenPermit,
                    bankLicenseImage,
                    ContextCompat.getDrawable(mContext, R.drawable.icon_navbar_add)
                )
            }
        })
    }

    override fun eventHandling() {
        setOnclickNoRepeat(
            ivIdCardPositiveSide, ivIdCardNegativeSide, ivHandWithIdCard,
            ivOpenPermit, ivShopLicense, btnSubmitApply, tvShopType,
            countryCodePicker, tvShopAddress, tvShopCategory, countryCode
        ){v->
            when (v) {
                ivIdCardPositiveSide -> {
                    openPicAlum(REQUEST_CODE_IDCARD_FRONT)
                }
                ivIdCardNegativeSide -> {
                    openPicAlum(REQUEST_CODE_IDCARD_BACK)
                }
                ivHandWithIdCard -> {
                    openPicAlum(REQUEST_CODE_IDCARD_HANDON)
                }
                ivOpenPermit -> {
                    openPicAlum(REQUEST_CODE_BANK_LICENSE)
                }
                ivShopLicense -> {
                    openPicAlum(REQUEST_CODE_BUSINESS_LICENSE)
                }
                countryCodePicker, tvShopAddress -> {
                    areaDialog = BottomDialog(this, 5)
                    viewModel.getRegionList(null)
                }
                tvShopType -> {
                    genderDialog.setBtnStr(
                        getString(R.string.individual),
                        getString(R.string.enterprise)
                    )
                    genderDialog.show()
                }
                tvShopCategory -> {
                    viewModel.getAllStroeCate()
                }
                btnSubmitApply -> {
                    when {
                        etShopName.text.isNullOrEmpty() -> XToast.normal(getString(R.string.please_enter_shop_name))
                        categoryId == -1 -> XToast.normal(getString(R.string.pls_choose_sale_cate))
                        etContactPerson.text.isNullOrEmpty() -> XToast.normal(getString(R.string.name_tip_2))
                        etContactWay.text.isNullOrEmpty() -> XToast.normal(getString(R.string.enter_phone_number))
                        regionId == -1 -> XToast.normal(getString(R.string.please_choose_address))
                        etDetailAddress.text.isNullOrEmpty() -> XToast.normal(getString(R.string.pleaser_input_detail_by_area))
                        identityFrontImage.isEmpty() -> XToast.normal(getString(R.string.pls_upload_idcard_front))
                        identityBackImage.isEmpty() -> XToast.normal(getString(R.string.pls_upload_idcard_back))
                        holdingIdentityImage.isEmpty() -> XToast.normal(getString(R.string.pls_upload_idcard_handon))
                        else -> {
                            if (shopType == getString(R.string.enterprise)) {
                                if (businessLicenseImage.isEmpty())
                                    XToast.normal(getString(R.string.pls_upload_businesslicenseimage))
                                if (bankLicenseImage.isEmpty())
                                    XToast.normal(getString(R.string.pls_upload_banklicenseimage))
                            }
                            val params = HashMap<String, Any>()
                            params["name"] = etShopName.text.toString()
                            params["type"] = shopType
                            params["category"] = mapOf(Pair("id", categoryId))
                            params["contactName"] = etContactPerson.text.toString()
                            params["contactPhone"] = etContactWay.text.toString()
                            params["region"] = mapOf(Pair("id", regionId))
                            params["address"] = etDetailAddress.text.toString()
                            params["identityFrontImage"] = identityFrontImage
                            params["identityBackImage"] = identityBackImage
                            params["holdingIdentityImage"] = holdingIdentityImage
                            if (shopType == getString(R.string.enterprise)) {
                                params["businessLicenseImage"] = businessLicenseImage
                                params["bankLicenseImage"] = bankLicenseImage
                            }
                            viewModel.dredgeStore(params)
                        }
                    }
                }
                countryCode -> {
                    AreaCodePopup(this){
                        countryCode.text = it
                        defaultAreaCode = it.replace("+","")
                    }.showPopupWindow()
                }
            }
        }
        picDialog.onOneClick = {
            PictureUtils.openCameraRectangle(mContext, requestCode)
        }
        picDialog.onTwoClick = {
            PictureUtils.openAluamOneRectangle(mContext, requestCode)
        }
        genderDialog.onOneClick = {
            llOpenPermitAndShopLicense.visibility = View.GONE
            shopType = getString(R.string.individual)
            tvShopType.text = shopType
        }
        genderDialog.onTwoClick = {
            llOpenPermitAndShopLicense.visibility = View.VISIBLE
            shopType = getString(R.string.enterprise)
            tvShopType.text = shopType
        }
    }

    private fun openPicAlum(requestCode: Int) {
        this.requestCode = requestCode
        AndPermission.with(this)
            .runtime()
            .permission(Permission.Group.CAMERA, Permission.Group.STORAGE)
            .onDenied {
                if (AndPermission.hasAlwaysDeniedPermission(this, it)) {
                    // 这些权限被用户总是拒绝。
                    XToast.normal(getString(R.string.request_necessary_permissions))
                }
            }
            .onGranted {
                picDialog.show()
            }.start()
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == Activity.RESULT_OK) {
            when (requestCode) {
                this.requestCode -> {
                    val path = PictureSelector.obtainMultipleResult(data)[0].cutPath
                    viewModel.uploadImage(path)
                }
            }
        }
    }


    override fun handleEvent(msg: MessageModel) {
        when (msg.code) {
            1 -> {
                val imageUrl = NetUrl.FILE_PROFILE + msg.obj as String
                when (this.requestCode) {
                    REQUEST_CODE_IDCARD_FRONT -> {
                        identityFrontImage = imageUrl
                        setNomalImageUrl(
                            ivIdCardPositiveSide,
                            identityFrontImage,
                            ContextCompat.getDrawable(mContext, R.drawable.default_image)
                        )
                    }
                    REQUEST_CODE_IDCARD_BACK -> {
                        identityBackImage = imageUrl
                        setNomalImageUrl(
                            ivIdCardNegativeSide,
                            identityBackImage,
                            ContextCompat.getDrawable(mContext, R.drawable.default_image)
                        )
                    }
                    REQUEST_CODE_IDCARD_HANDON -> {
                        holdingIdentityImage = imageUrl
                        setNomalImageUrl(
                            ivHandWithIdCard,
                            holdingIdentityImage,
                            ContextCompat.getDrawable(mContext, R.drawable.default_image)
                        )
                    }
                    REQUEST_CODE_BUSINESS_LICENSE -> {
                        businessLicenseImage = imageUrl
                        setNomalImageUrl(
                            ivShopLicense,
                            businessLicenseImage,
                            ContextCompat.getDrawable(mContext, R.drawable.default_image)
                        )
                    }
                    REQUEST_CODE_BANK_LICENSE -> {
                        bankLicenseImage = imageUrl
                        setNomalImageUrl(
                            ivOpenPermit,
                            bankLicenseImage,
                            ContextCompat.getDrawable(mContext, R.drawable.default_image)
                        )
                    }
                }
            }
            3 -> {
                UniversalityResultActivity.openActivity(
                    mContext,
                    UniversalityResultActivity.FROM_OPEN_STORE
                )
                finish()
            }
            2 -> {
                areaDialog?.run {
                    this.setDataRegion(msg.obj as MutableList<RegionDto>)
                    this.setOnAddressSelectedListener(object : SelectedListener {
                        override fun onAddressSelected(selectAbles: ArrayList<RegionDto>?) {
                            selectAbles?.run {
                                if (this.size == 1) {//表明只有国家可选
                                    regionId = this[0].id
                                    mBinding.tvShopAddress.text = this[0].name
                                    mBinding.countryCodePicker.text = this[0].name
                                } else {//表明有国家和下属地区
                                    var area = ""
                                    for ((index, selectAble) in this.withIndex()) {
                                        if (index == 0) {
                                            mBinding.countryCodePicker.text = selectAble.name
                                        } else {
                                            area = area + selectAble.name + "  "
                                        }
                                        regionId = selectAble.id
                                    }
                                    mBinding.tvShopAddress.text = area
                                    areaDialog = null
                                }
                            }
                        }

                        override fun onClickOnEach(selectAble: RegionDto?) {
                            viewModel.getRegionList(selectAble?.id)
                        }
                    })
                    if (this.isShowing) return
                    this.show()
                }
            }
            4 -> {
                CategroyPopup(mContext, (msg.obj as MutableList<FirstCategoryDto>)) {
                    categoryId = it.id
                    tvShopCategory.text = it.name
                }.showPopupWindow()
            }
        }
    }

    companion object {
        const val REQUEST_CODE_IDCARD_FRONT = 10001
        const val REQUEST_CODE_IDCARD_BACK = 10002
        const val REQUEST_CODE_IDCARD_HANDON = 10003
        const val REQUEST_CODE_BUSINESS_LICENSE = 10004
        const val REQUEST_CODE_BANK_LICENSE = 10005
        fun openActivity(mContext: BaseActivity<*, *>) {
            mContext.startActivity(null, DredgeStoreActivity::class.java)
        }
    }
}
